package forms;

import dataBase.DataBase;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Logger;
import javax.swing.ComboBoxModel;
import models.ResultSetTableModel;


public class Display extends javax.swing.JFrame {

    static private ResultSetTableModel tableModel;
    static final String DEFAULT_QUERY = "SELECT a.nome_item AS Título, act.nome_acervo_tipo AS Categoria, g.nome_genero AS Gênero FROM acervo a JOIN acervo_tipos act ON act.id_acervo_tipo = a.id_acervo_tipo JOIN generos g ON g.id_genero = a.id_genero ORDER BY a.nome_item";
    DataBase db = new DataBase();

    public Display() throws SQLException, ClassNotFoundException {
        tableModel = new ResultSetTableModel(db.getConnection(), DEFAULT_QUERY);
        initComponents();
        this.setJcb();
    }
    
    public void setJcb() throws SQLException {
        tableModel.connection.setAutoCommit(false);
        try {
            Statement st = tableModel.connection.createStatement();
            ResultSet rs = st.executeQuery("SELECT nome_genero FROM generos");
            ResultSetMetaData meta = rs.getMetaData();
            while (rs.next()) {
                for (int i = 1; i <= meta.getColumnCount(); i++) {
                    jcbGereno.addItem(rs.getObject(i));
                }
            }

            rs = st.executeQuery("SELECT nome_acervo_tipo FROM acervo_tipos");
            meta = rs.getMetaData();
            while (rs.next()) {
                for (int i = 1; i <= meta.getColumnCount(); i++) {
                    jcbTipo.addItem(rs.getObject(i));
                }
            }    
        }
        catch (Exception ex) {
            System.out.println(ex);
            tableModel.connection.rollback();
        }
        tableModel.connection.setAutoCommit(true);
    }
    
    

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        javax.swing.JTable jTable = new javax.swing.JTable();
        jbtTodos = new javax.swing.JButton();
        jbtBusca = new javax.swing.JButton();
        jcbTipo = new javax.swing.JComboBox();
        jtfNome = new javax.swing.JTextField();
        jcbGereno = new javax.swing.JComboBox();
        jlbTipoVideo = new javax.swing.JLabel();
        jlbGenero = new javax.swing.JLabel();
        jlbNome = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jbtInsert = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTable.setModel(tableModel);
        jTable.setName(""); // NOI18N
        jScrollPane1.setViewportView(jTable);

        jbtTodos.setText("Exibir Todos");
        jbtTodos.setName("btnExecutar"); // NOI18N
        jbtTodos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtTodosActionPerformed(evt);
            }
        });

        jbtBusca.setText("Listar");
        jbtBusca.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtBuscaActionPerformed(evt);
            }
        });

        jtfNome.setToolTipText("Digite aqui o nome completo ou parcial");

        jlbTipoVideo.setText("Tipo Vídeo");

        jlbGenero.setText("Gênero");

        jlbNome.setText("Busca por Nome");

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel1.setText("Locadora - Acervo");

        jbtInsert.setText("Inserir");
        jbtInsert.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jbtInsertMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jlbNome)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jlbTipoVideo)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jcbTipo, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(47, 47, 47)
                                        .addComponent(jlbGenero)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jcbGereno, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                    .addComponent(jtfNome, javax.swing.GroupLayout.PREFERRED_SIZE, 338, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(18, 18, 18)
                                .addComponent(jbtBusca)
                                .addGap(18, 18, 18)
                                .addComponent(jbtInsert)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 44, Short.MAX_VALUE)
                                .addComponent(jbtTodos))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(248, 248, 248)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(21, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addGap(25, 25, 25)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jcbTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jcbGereno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jlbTipoVideo)
                    .addComponent(jlbGenero))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jlbNome)
                .addGap(1, 1, 1)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jtfNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbtBusca)
                    .addComponent(jbtTodos)
                    .addComponent(jbtInsert))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void jbtTodosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtTodosActionPerformed
        try {
            // TODO add your handling code here:
            tableModel.setDefaultQuery(DEFAULT_QUERY);

        } catch (SQLException ex) {
            System.out.println(ex);
        }

    }//GEN-LAST:event_jbtTodosActionPerformed

    private void jbtBuscaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtBuscaActionPerformed
        try {
            tableModel.setSearch(jtfNome.getText(), jcbGereno.getSelectedIndex(), jcbTipo.getSelectedIndex());
        }
        catch (SQLException ex) {
            System.out.println(ex);
        }
    }//GEN-LAST:event_jbtBuscaActionPerformed

    private void jbtInsertMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jbtInsertMouseClicked
        // TODO add your handling code here:
        try {
            tableModel.setInsert(jcbGereno.getSelectedIndex(), jcbTipo.getSelectedIndex(), jtfNome.getText());
            tableModel.setDefaultQuery(DEFAULT_QUERY);
        }
        catch (Exception ex) {
            System.out.println(ex);
        }
    }//GEN-LAST:event_jbtInsertMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Display.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Display.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Display.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Display.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    new Display().setVisible(true);
                } catch (SQLException ex) {
                    System.out.println(ex);
                } catch (ClassNotFoundException ex) {
                    System.out.println(ex);
                }
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbtBusca;
    private javax.swing.JButton jbtInsert;
    private javax.swing.JButton jbtTodos;
    private javax.swing.JComboBox jcbGereno;
    private javax.swing.JComboBox jcbTipo;
    private javax.swing.JLabel jlbGenero;
    private javax.swing.JLabel jlbNome;
    private javax.swing.JLabel jlbTipoVideo;
    private javax.swing.JTextField jtfNome;
    // End of variables declaration//GEN-END:variables
}
